<?php

namespace App\Supports\Payment\Methods\Goldcoin;

use Exception;
use Carbon\Carbon;
use App\Models\GoldCharge;
use App\Events\GoldChargePaidEvent;
use Illuminate\Support\Facades\DB;
use App\Supports\Payment\Methods\Method;
use App\Supports\Payment\Contracts\MethodPay;
use Illuminate\Validation\ValidationException;

class PayGoldCharge extends Method implements MethodPay
{

	protected function isCoinEnough($order)
	{
		return $order->user->isGoldCoinsEnough($order->total_amount);
	}
	
	public function validate($order = null)
	{
		if ($order->isPaid()) {
			fail('目标订单已支付');
		}

		if (!$this->isCoinEnough($order)) {
			fail('可用账户余额不足');
		}
	}
	
	public function info($order = null) {}
	
	public function pay($order = null)
	{
		

		$this->validate($order);

		return DB::transaction(function () use ($order) {
			$charge = GoldCharge::lockForUpdate()->find($order->id);
			$charge->update(['paid_at' => Carbon::now(), 'paid_method' => 'goldcoin']);
			$coins = $charge->total_amount;
            $data = ['charge_id' => $charge->id];
            account_coins($charge->user)->minusChargePaid($coins, $data);
			event(new GoldChargePaidEvent($charge));
			$charge->unsetRelations();
			return $charge;
		});
	}
} 
